package com.EM1.www.servlet;
import com.EM1.www.constant.constant;
import com.EM1.www.dao.ConnectUser;
import com.EM1.www.po.User;
import com.EM1.www.service.CheckUSer;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;

@WebServlet("/Login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username=request.getParameter("username");
        String password=request.getParameter("password");
        String remember=request.getParameter("remember");
        String checkcode=request.getParameter("checkcode");
        CheckUSer checkUSer=new CheckUSer();
        System.out.println(remember);
        String warn= null;
        try {
            warn = checkUSer.verifyUSer(username,password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }HttpSession session = request.getSession();
        String rightcheckcode = (String) session.getAttribute("checkcode");
        if(!checkcode.equalsIgnoreCase(rightcheckcode)){
            warn="验证码不正确";}
        if(warn!=null){
            request.setAttribute("warn",warn);
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else{
            if (remember!=null) {
                 username = URLEncoder.encode(username, "UTF-8");
                System.out.println(username);
                System.out.println(password);
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie=new Cookie("password",password);
                usernameCookie.setMaxAge(7 * 24 * 60 * 60);
                passwordCookie.setMaxAge(7*24*60*60);
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }
            ConnectUser connectUser=new ConnectUser();
            User user=null;
            try {
                user = connectUser.selectusername(username);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            session.setAttribute("user",user);

            if(user.isIsteacher()){
            response.sendRedirect("http://localhost:8080/ExaminationManagement1_war/TeacherMain");
            }else {
                response.sendRedirect("http://localhost:8080/ExaminationManagement1_war/StudentMain");
            }

        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
